package cshi.network;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.IntBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;

public class TestNIO {
	public static void main(String[] args)
	{
		test_bytebuf();
		/*
		test_intbuffer();
		try {
			test_channel();
		} catch (Exception e) {
			// TODO: handle exception
		}
		*/
	}
	
	public static void test_intbuffer() 
	{
		
		IntBuffer buffer = IntBuffer.allocate(8);

		for (int i = 0; i < buffer.capacity(); ++i) {
			int j = 2 * (i + 1);
			
			buffer.put(j);
		}


		buffer.flip();

		while (buffer.hasRemaining()) {

			int j = buffer.get();
			System.out.print(j + "  ");
		}

	}	

	static private final byte message[] = { 65, 111, 109, 101, 32,  
	        98, 121, 116, 101, 115, 46 };  
	public static void test_channel() throws Exception
	{
		FileInputStream fis = new FileInputStream("d:\\tmp\\test.c");
		FileChannel fc = fis.getChannel();
		

		ByteBuffer bb = ByteBuffer.allocate(1024);
		

		fc.read(bb);
		
		bb.flip();
		
		while (bb.remaining() > 0) {
			byte b = bb.get();
			System.out.print((char)b);
			//Thread.sleep(300);
		}
		fis.close();
		
		FileOutputStream fos = new FileOutputStream("d:\\tmp\\tmp.txt");
		fc = fos.getChannel();
		//ByteBuffer outbuf = ByteBuffer.allocate(1024);
		
		bb.clear();
		for(int i=0; i<message.length; i++)
			bb.put(message[i]);
				
		bb.flip();
		fc.write(bb);
		fos.close();
		
		RandomAccessFile raf = new RandomAccessFile("d:\\tmp\\tmp2.txt", "rw");
		fc = raf.getChannel();
		
		MappedByteBuffer mbb = fc.map(FileChannel.MapMode.READ_WRITE, 0, 1024);
		mbb.put(0,(byte)97);//a
		mbb.put(1023,(byte)122);//z
		raf.close();
	}
	
	static void test_bytebuf(){
		byte[] tmp = new byte[]{0x00,0x00,0x00,(byte)0x80};
		ByteBuf byteBuf = Unpooled.wrappedBuffer(tmp);
		ByteBuf bb = byteBuf.order(ByteOrder.LITTLE_ENDIAN);
		
		
		System.out.println(bb.order());
		//int n2 = bb.readInt();
		long n2 = bb.readUnsignedInt();
		System.out.printf("%d", n2);
		
		/*
		for (int i=0; i<byteBuf.capacity(); i++){
			byte b = byteBuf.getByte(i);
			
			System.out.println(i);
		}
		*/
	}
	

}
